<!--
 * @Author: yhy
 * @Date: 2022-03-16 15:43:04
 * @LastEditTime: 2022-03-18 10:35:22
 * @LastEditors: yhy
 * @Description:
-->
<template>
  <div>
    <van-nav-bar title="黑马头条-登录" />
    <div class="box">
      <van-form @submit="onSubmit">
        <van-field
          v-model="user.mobile"
          required
          name="mobile"
          label="手机号"
          placeholder="手机号"
          :rules="[
            {
              required: true,
              message: '请填写正确11位手机号',
              pattern: /^1[3-9]\d{9}$/,
            },
          ]"
        />
        <!-- 密码 246810 -->
        <van-field
          v-model="user.code"
          required
          type="password"
          name="code"
          label="密码"
          placeholder="密码"
          :rules="[
            {
               required: true,
               message: '请填写正确6位密码',
               pattern: /^\d{6}$/ },
          ]"
        />
        <div style="margin: 16px">
          <van-button round block type="info" native-type="submit"
           :disabled= 'isLoading'
           :loading= 'isLoading'
           loading-text="登陆ing~"
            >登陆</van-button
          >
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
import { loginApi } from '@/api'
import { Notify } from 'vant'
import { setToken } from '@/utils/token'
export default {
  data () {
    return {
      user: {
        mobile: '13888888888',
        code: '246810'
      },
      isLoading: false
    }
  },
  methods: {
    // 发起登陆请求
    async onSubmit (values) {
      // 请求开始后 禁用登陆按钮
      this.isLoading = true
      // console.log('submit', values)
      try {
        // 成功后触发
        const res = await loginApi(values)
        console.log(res)
        // 设置token
        setToken(res.data.data.token)
        Notify({ type: 'success', message: '登陆成功~' })
        // 跳转到首页
        this.$router.replace({
          path: '/layout/home'
        })
      } catch (err) {
        // 失败后触发
        Notify('账号或密码错误!')
      }
      // 请求结束后 重置button按钮
      this.isLoading = false
    }
  }
}
</script>

<style lang='less' scoped>
.box {
  margin-top: 5vh;
}
</style>
